import 'dart:convert';

import 'package:amway_superapp_creator_plugin/analysis/zhuge_portal.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/config/config_function.dart';
import 'package:amway_superapp_creator_plugin/config/enum_config.dart';
import 'package:amway_superapp_creator_plugin/models/create_user_info_model.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/routers/routes.dart';
import 'package:amway_superapp_creator_plugin/utils/event_bus_utils.dart';
import 'package:amway_superapp_creator_plugin/utils/sp_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/home/create_home_viewmodel.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:amway_superapp_creator_plugin/widget/customer_share_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_flavor/flutter_flavor.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';
import '../../view_state.dart';
import 'guide_list_widget.dart';
import 'package:amway_superapp_creator_plugin/widget/back_button.dart';
/**
 * 小站首页
 */

class CreateHome extends StatefulWidget {
  var amwayAda;
  var amwayId;
  var phone;

  CreateHome({this.amwayAda, this.amwayId, this.phone});

  @override
  _CreateHomeState createState() => _CreateHomeState();
}

class _CreateHomeState extends State<CreateHome> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<CreateHomeViewModel>(
      model: CreateHomeViewModel(api: Provider.of(context)),
      onModelReady: (model) async {
        model.getUserInfo(widget.amwayAda);
        model.queryShareLink(amwayAda: widget.amwayAda);
        model.queryModelConfiginfo(widget.amwayAda);
        ZhugePortalAnalysis.portalCreatorPage(model.isOpenCreate);
        ZhugePortalAnalysis.userguideListPage(model.isOpenCreate);
      },
      builder: (context, model, child) =>
          Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              backgroundColor: ColorsConfig.c_CDF9FA,
              centerTitle: true,
              elevation: 0,
              brightness: Brightness.light,
              leading: BackButtion(
                onTap: () => _back(context),
              ),
              title: Text(
                '创玩小站',
                style: TextStyle(
                  color: ColorsConfig.homeTitleColor,
                  fontSize: ScreenUtil().setSp(24),
                ),
              ),
            ),
            body: WillPopScope(
              onWillPop: () => _back(context),
              child: _buildBody(context, model),
            ),
          ),
    );
  }

  _back(BuildContext context) {
    Map<String, dynamic> map = {};
    map['option'] = NotifySuperOption.REFRSH;
    eventBus.fire(NoticesEvent(map));
    Application.router.pop(context);
  }

  CreateUserInfoModel info;

  Widget _buildBody(BuildContext context, CreateHomeViewModel model) {
    info = model.createUserInfoModel != null
        ? model.createUserInfoModel
        : CreateUserInfoModel();
    return model.state == ViewState.Busy
        ? Center(
      child: CircularProgressIndicator(),
    )
        : Container(
      color: Colors.white,
      child: Container(
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          reverse: false,
          padding: EdgeInsets.all(0.0),
          // physics: BouncingScrollPhysics(),
          child: Column(
            children: [
              _buildUserInfo(context, model),
              Container(
                color: Colors.white,
                child: new GuideListWidget(false),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUserInfo(BuildContext context, CreateHomeViewModel model) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(20),
          right: ScreenUtil().setWidth(20),
          top: ScreenUtil().setHeight(20),
          bottom: ScreenUtil().setHeight(20)),
      decoration: new BoxDecoration(
        image: new DecorationImage(
          fit: BoxFit.fill,
          image: new AssetImage("picture/home_bg.png",
              package: 'amway_superapp_creator_plugin'),
          //这里是从assets静态文件中获取的，也可以new NetworkImage(）从网络上获取
        ),
      ),
      child: Column(
        children: [
          Row(
            children: [
              CircleAvatar(
                  radius: ScreenUtil().setWidth(32),
                  backgroundColor: Colors.white,
                  backgroundImage:NetworkImage(model.getUserHeadUrl()),
              ),
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(
                      left: ScreenUtil().setWidth(16),
                      right: ScreenUtil().setWidth(16)),
                  child: model.isOpenCreate
                      ? Text(
                    model.createUserInfoModel.nick,
                    softWrap: true,
                    textAlign: TextAlign.left,
                    style: TextStyle(
                      color: ColorsConfig.c_396E75,
                      fontSize: ScreenUtil().setSp(24),
                    ),
                  )
                      : Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        alignment: Alignment.centerLeft,
                        child: InkWell(
                          onTap: () {
                            SpUtil.getData(
                                "${SpUtil.user_data}${widget.amwayAda}")
                                .then((value) {
                              _jumpEditer(model, context,
                                  hasDraft: value == null ? false : true);
                            });
                          },
                          child: Text(
                            "开始编辑我的资料﹥",
                            style: TextStyle(
                              color: ColorsConfig.leftBackColor,
                              fontSize: ScreenUtil().setSp(18),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        child: Text("编辑资料后可以开启我的创玩小站哦",
                            style: TextStyle(
                              color: ColorsConfig.leftBackColor,
                              fontSize: ScreenUtil().setSp(14),
                            )),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
          Container(
            child: Column(
              children: [
                buildeMyMenu(model, context),
                homeBottomMenu(context, model),
                createGuideInfo(context, model),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget buildeMyMenu(CreateHomeViewModel model, BuildContext context) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                ZhugePortalAnalysis.creatorClickTab('编辑资料', 'Prot页');
                SpUtil.getData("${SpUtil.user_data}${widget.amwayAda}")
                    .then((value) {
                  _jumpEditer(model, context,
                      hasDraft: value == null ? false : true);
                });
              },
              child: createItem("编辑资料", "picture/icon_home_editer.png",
                  model.isUserInfoReviewState),
            ),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(16),
          ),
          Expanded(
            child: InkWell(
              child: createItem("设置小站", "picture/icon_set_create.png",
                  model.isOpenCreate ? model.isUpassModel : false,
                  isClose: !model.isOpenCreate),
              onTap: () {
                ZhugePortalAnalysis.creatorClickTab('设置小站', 'Prot页');
                if (model.isOpenCreate) {
                  Map<String, dynamic> parameters = {
                    'amwayAda': widget.amwayAda,
                    'amwayId': widget.amwayId,
                    'identityMarks': model.createUserInfoModel.identityMarks,
                  };
                  Application.router
                      .navigateTo(context, Routes.mainSettings,
                      routeSettings: RouteSettings(arguments: parameters))
                      .then((value) {
                    model.queryModelConfiginfo(widget.amwayAda);
                  });
                }
              },
            ),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(16),
          ),
          Expanded(
            child: InkWell(
              child: createItem("修改配色", "picture/icon_update_color.png", false,
                  isClose: true),
              onTap: () {
                ZhugePortalAnalysis.creatorClickTab('修改配色', 'Prot页');
                //  Navigator.pop(context);
              },
            ),
          ),
        ],
      ),
    );
  }

  void _jumpEditer(CreateHomeViewModel model, BuildContext context,
      {bool hasDraft = false}) {
    Map<String, dynamic> parameters = {
      'createUserInfoModel': model.createUserInfoModel,
      'amwayAda': widget.amwayAda,
      'amwayId': widget.amwayId,
      'phone': widget.phone,
      'hasDraft': hasDraft
    };

    Application.router
        .navigateTo(
      context,
      Routes.editdata,
      routeSettings: RouteSettings(arguments: parameters),
    )
        .then((value) {
      if (value == null) {
        SpUtil.getData("${SpUtil.local_user_data}${widget.amwayAda}")
            .then((value) {
          if (null != value) {
            Map<String, dynamic> response = json.decode(value);
            CreateUserInfoModel infoModel =
            CreateUserInfoModel.fromJson(response);
            if (model.createUserInfoModel != infoModel) {
              model.createUserInfoModel = infoModel;
            }
          }
        });
      } else {
        if (value == 1) {
          model.getUserInfo(widget.amwayAda, isVisible: false);
        } else {
          model.createUserInfoModel = value;
        }
      }
    });
  }

  ///首页菜单
  Widget createItem(String lable,
      String path,
      bool isShowRedDots, {
        bool isClose = false,
      }) {
    return Container(
      width: ScreenUtil().setWidth(114),
      height: ScreenUtil().setWidth(134),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(12))),
            child: Container(
              child: Stack(
                children: [
                  Positioned(
                    bottom: 0,
                    right: 0,
                    child: Container(
                      child: Image.asset(
                        path,
                        fit: BoxFit.fill,
                        width: ScreenUtil().setWidth(85),
                        height: ScreenUtil().setWidth(85),
                        package: 'amway_superapp_creator_plugin',
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.topCenter,
                    child: Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
                      child: Text(
                        lable,
                        style: TextStyle(
                            color: ColorsConfig.c_2c2c2c,
                            fontSize: ScreenUtil().setSp(14),
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                  if (isClose)
                    Positioned(
                      right: 0,
                      left: 0,
                      top: 0,
                      bottom: 0,
                      child: Container(
                        decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.8),
                            borderRadius:
                            BorderRadius.all(Radius.circular(12))),
                      ),
                    )
                ],
              ),
            ),
          ),
          Positioned(
            right: 5,
            top: 5,
            child: isShowRedDots
                ? Icon(
              Icons.circle,
              size: 10,
              color: Colors.red,
            )
                : Container(),
          )
        ],
      ),
    );
  }

//底部菜单
  Widget homeBottomMenu(BuildContext context, CreateHomeViewModel model) {
    return Container(
      child: Card(
        margin: EdgeInsets.symmetric(vertical: ScreenUtil().setHeight(16)),
        color: Colors.white.withOpacity(0.5),
        elevation: 0,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(12.0))),
        //设置圆角
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: ScreenUtil().setHeight(13)),
          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: InkWell(
                  onTap: () {
                    if (!model.isOpenCreate) {
                      ToastUtils.showShortToast("请先完成编辑资料");
                      return;
                    }
                    String path =
                        FlavorConfig.instance.variables["creatorPath"] +
                            widget.amwayAda;
                    int miniProgramType =
                    FlavorConfig.instance.variables["miniProgramType"];
                    String userName =
                    FlavorConfig.instance.variables["creatorUserName"];
                    Map<String, dynamic> shareData = {};
                    shareData['path'] = path;
                    shareData['miniProgramType'] = miniProgramType;
                    shareData['userName'] = userName;
                    shareData['shareAction'] = WeChatScene.LANUCH;
                    shareData['option'] = NotifySuperOption.SHARE;
                    ConfigFunctionCallBack.optionCallback?.call(shareData);
                    //eventBus.fire(NoticesEvent(shareData));
                    ZhugePortalAnalysis.creatorClickToShop("port页");

                    //  CustomerShareWechat.launchWeChatMiniProgram(widget.amwayAda);
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        child: Image.asset(
                          model.isOpenCreate
                              ? "picture/icon_join_create.png"
                              : "picture/icon_noopen_join.png",
                          package: 'amway_superapp_creator_plugin',
                        ),
                      ),
                      Container(
                        margin:
                        EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                        child: Text(
                          '进入小站',
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(16),
                              fontWeight: FontWeight.w600,
                              color: model.isOpenCreate
                                  ? ColorsConfig.c_2c2c2c
                                  : ColorsConfig.c_2c2c2c.withOpacity(0.1)),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
            Container(
              height: 20,
              color: Colors.grey[500],
              width: 0.5,
            ),
            Expanded(
              flex: 1,
              child: InkWell(
                onTap: () {
                  if (!model.isOpenCreate) {
                    ToastUtils.showShortToast("请先完成编辑资料");
                    return;
                  }
                  ZhugePortalAnalysis.creatorClickShareShop('port页');
                  CustomerShareView.showShareView(
                      context: context,
                      ada: widget.amwayAda,
                      shareTitle: model.createUserInfoModel.nick + '邀请你',
                      shareThumbnail: 'picture/img_share_port.png',
                      shareLink: model.shareLink);
                },
                child: Center(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        child: Image.asset(
                          model.isOpenCreate
                              ? "picture/icon_share_create.png"
                              : "picture/icon_noopen_share.png",
                          package: 'amway_superapp_creator_plugin',
                        ),
                      ),
                      Container(
                        margin:
                        EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                        child: Text(
                          '分享小站',
                          style: TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: ScreenUtil().setSp(16),
                              color: model.isOpenCreate
                                  ? ColorsConfig.c_2c2c2c
                                  : ColorsConfig.c_2c2c2c.withOpacity(0.1)),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )
          ]),
        ),
      ),
    );
  }

  Widget createGuideInfo(BuildContext context, CreateHomeViewModel model) {
    return Container(
      padding: EdgeInsets.only(
          top: ScreenUtil().setHeight(46), bottom: ScreenUtil().setHeight(10)),
      child: Row(
        children: [
          Expanded(
            flex: 1,
            child: Container(
              child: Text(
                '创玩小站使用指南',
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: ScreenUtil().setSp(18),
                    color: ColorsConfig.c_2c2c2c),
              ),
            ),
          ),
          InkWell(
            onTap: () {
              ZhugePortalAnalysis.creatorClickMore('prot页');
              Application.router.navigateTo(context, Routes.guidelist);
            },
            child: Row(
              children: [
                Container(
                  child: Text(
                    '更多',
                    style: TextStyle(
                        fontSize: ScreenUtil().setSp(14),
                        color: ColorsConfig.c_802c2c2c),
                  ),
                ),
                Image.asset(
                  "picture/icon_arrow_right.png",
                  package: "amway_superapp_creator_plugin",
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
